package com.example.newsmanager.handler;

import com.example.newsmanager.common.Result;
import com.example.newsmanager.exception.TokenEmptyException;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice
public class
GlobalExceptionHandler {
    @ExceptionHandler(TokenEmptyException.class)
    public Result<String> handleTokenEmptyException(TokenEmptyException e) {
        return Result.fail(666,"请先登录");
    }
    @ExceptionHandler(BindException.class)
    public Result<String> handleBindException(HttpServletRequest request,BindException exception) {
        List<FieldError> allErrors = exception.getFieldErrors();
        StringBuilder sb = new StringBuilder();
        for (FieldError errorMessage : allErrors) {
            sb.append(errorMessage.getField()).append(": ").append(errorMessage.getDefaultMessage()).append(", ");
        }
        System.out.println(sb.toString());
        return Result.fail(999,"参数不合法",sb.toString());
    }
}
